<?php

namespace App\Console\Commands;

use App\Http\Controllers\Resource\CxzxController;
use App\Models\ResourceBusinessName;
use App\Models\ResourceCxzx;
use App\Models\ResourceTypeCxzx;
use App\Models\ResourceTypeExternal;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

/**
 * 畅享之星数据同步到数据库
 */
class CxzxMysqlData extends Command
{

    // 使用 命令行执行  php artisan command:CxzxMysqlData

    //  protected $data_sync_hour = 0; //0 表示不限制时间，全同步，其余表示 更改时间  单位小时
    protected $limit = 100; //每页限制条数
    protected $up_start_page = 1; //开始页，默认为 1

    protected $down_month = 1; //下架数据，同步几个月前的数据，默认是 3 个月之内的数据

    protected $resource_business_id = 7; //资源商id


    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:CxzxMysqlData';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步畅想之星资源数据到数据库';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $resourceBusinessNameModel = new  ResourceBusinessName();
        $resource_business_name_info = $resourceBusinessNameModel->where('id', $this->resource_business_id)->where('is_del', 1)->first();
        if (empty($resource_business_name_info)) {
            Log::channel('cxzxcmdlog')->debug('资源商不存在或已被删除');
            die;
        }
        try {
            //先同步数据
            $obj = new CxzxController();
            $resourceTypeExternalModel = new ResourceTypeExternal();
            $resourceModel = new ResourceCxzx();

            $get_type_list = $obj->getResourceType(); //获取所有分类
            //全部先放入我们自己的服务器
            if ($get_type_list) {
                $resourceTypeCxzxModel = new ResourceTypeCxzx();
                $resourceTypeCxzxModel->addData($get_type_list);
            }

            //数据太多，可能会导致更新到一半断掉
            $request_page =  $resource_business_name_info['request_page'];
            $request_time =  $resource_business_name_info['request_time'];
            if (!empty($request_page)) {
                $this->up_start_page = $request_page; //更新上架页数
            }

            $node = 1; //全更新  2 增量更新
            if ($request_time && $request_page == 1) {
                $node = 2;
                $this->up_start_page = 1; //重置成 1；//增量都是从第一页开始
            }

            if ($node == 2) {
                //走增量数据
                $total_data = $obj->getResourceIncreaseList('All', date('Y-m-d H:i:s', strtotime("-3 day", strtotime($request_time))), date('Y-m-d h:i:s'), 1, 'Twenty');
            } else {
                //全同步
                $total_data = $obj->getResourceList('All', 'ALL', '', '', 1, 'Twenty');
            }

            if ($total_data) {
                $limit = $this->limit;
                $total = $total_data['Total'];
                $total_page = (int)ceil($total / $limit) + 1;

                Log::channel('cxzxcmdlog')->debug('全量同步' . $node . '上架数据开始，共' . $total_page . ' 页');

                //获取所有数据和现在更新的数据做对比，如果没有则删除，有则不做处理
                // $data_unique_id_all = $resourceModel->select('guid', 'data_unique_id')->where('resource_business_id', $this->resource_business_id)->where('is_del', 1)->get()->toArray();
                // $data_unique_id_all = array_column($data_unique_id_all, 'guid', 'data_unique_id');

                for ($i = $this->up_start_page; $i <= $total_page; $i++) {
                    if ($i % 5 == 0) {
                        sleep(2);
                    }
                    if ($node == 2) {
                        //走增量数据
                        $data = $obj->getResourceIncreaseList('All', date('Y-m-d H:i:s', strtotime("-3 day", strtotime($request_time))), date('Y-m-d h:i:s'), $i, 'OneHundred');
                    } else {
                        //全同步
                        $data = $obj->getResourceList('All', 'ALL', '', '', $i, 'OneHundred'); //获取总数据量
                    }
                    if ($data) {
                        $result_id = '';
                        foreach ($data['Data'] as $key => $val) {
                            //删除指定的值
                            //  unset($data_unique_id_all[$val['Id']]);
                            $cxzx_class_id = $val['Class'];
                            $cxzx_class_id = empty($cxzx_class_id) ? [] : $cxzx_class_id;
                            foreach ($cxzx_class_id as $k => $v) {
                                //获取我们系统对应的分类id信息
                                $self_type_info = $resourceTypeCxzxModel->where('original_id', $v)->where('is_del', 1)->first();
                                $type_id = '';
                                if ($self_type_info) {
                                    $type_id = $resourceTypeExternalModel->getTypeNameNoAdd([
                                        'name' => $self_type_info['type_name'],
                                        'level' => $self_type_info['level'],
                                        'resource_business_id' => $this->resource_business_id,
                                        'big_type_id' => 1,
                                        'original_id' => $self_type_info['original_id'],
                                    ]);
                                }
                                if ($type_id) {
                                    break; //只要获取到一个类型即可
                                }
                            }
                            $val['type_id'] = $type_id ?? null; //获取书籍小类
                            $val['big_type_id'] = 1; //大类  与资源管理系统一致
                            $val['data_unique_id'] = $val['Id']; //获取书籍小类
                            $result = $resourceModel->addData($val);
                            $result_id .= $result . '、';
                        }
                        //增量不更新页数
                        if ($node == 1) {
                            $resourceBusinessNameModel->where('id', $this->resource_business_id)->update(['request_page' => $i + 1]); //更新页数
                        }

                        Log::channel('cxzxcmdlog')->debug('全量同步上架数据，第 ' . $i . ' 页数据处理完毕: ' . $result_id);
                    } else {
                        //删除本地更新不存在的数据
                        // if (!empty($data_unique_id_all)) {
                        //     $result_id = '';
                        //     foreach ($data_unique_id_all as $key => $val) {
                        //         $del_id = $resourceModel->deleteData($key);
                        //         $result_id .= $del_id . '、';
                        //     }
                        //     Log::channel('cxzxcmdlog')->debug('删除本地更新不存在的数据，处理完毕: ' . $result_id);
                        // }

                        //同步到最后一页才重置
                        if ($i == $total_page && $node == 1) {
                            $resourceBusinessNameModel->where('id', $this->resource_business_id)->update(['request_page' => 1, 'request_time' => date('Y-m-d H:i:s')]); //重置页数
                        }
                        //数据太大才判断，数据量小不判断，主要解决接口莫名失败的情况
                        if ($i == $total_page) {
                            Log::channel('cxzxcmdlog')->debug('全量同步上架数据处理完毕: 页数: ' . $i);
                        } else {
                            Log::channel('cxzxcmdlog')->debug('全量同步上架数据出现异常: 页数: ' . $i);
                        }
                        break;
                    }
                }
            }
            //获取数据下架列表
            $down_total_data = $obj->downResourceList('All', date('Y-m-d H:i:s', strtotime("-" . $this->down_month . " month")), date('Y-m-d H:i:s'), 1, 'Twenty');
            if ($down_total_data) {
                $limit = $this->limit;
                $total = $down_total_data['Total'];
                $total_page = (int)ceil($total / $limit) + 1;
                for ($i = 1; $i <= $total_page; $i++) {
                    $down_data = $obj->downResourceList('All', date('Y-m-d H:i:s', strtotime("-" . $this->down_month . " month")), date('Y-m-d H:i:s'), $i, 'OneHundred'); //获取总数据量
                    if ($down_data) {
                        //直接删除数据
                        $result_id = '';
                        foreach ($down_data['Data'] as $key => $val) {
                            $del_id = $resourceModel->deleteData($val);
                            $result_id .= $del_id . '、';
                        }
                    }
                }
                Log::channel('cxzxcmdlog')->debug('全量同步下架数据，处理完毕: ' . $result_id);
            } else {
                Log::channel('cxzxcmdlog')->debug('暂无全量下架数据');
            }
            Log::channel('cxzxcmdlog')->debug('数据全部同步完成');
            // echo '数据全部同步完成';
            //更新同步时间
            $resourceBusinessNameModel->where('id', $this->resource_business_id)->update(['last_synch_time' => date('Y-m-d H:i:s')]);
        } catch (\Exception $e) {
            Log::channel('cxzxcmdlog')->debug('数据处理出现异常:' . $e->getMessage() . ';File:' . $e->getFile() . ';Line:' . $e->getLine() . ';');
        }
    }
}
